package com.wkm.chainchain.pbft.p2p;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.wkm.chainchain.pbft.common.PBFTMsgType;
import com.wkm.chainchain.pbft.msg.PBFTMsg;
import com.wkm.chainchain.pbft.node.Node;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;

@Slf4j
public class BlockchainWebSocketClient extends WebSocketClient {

    private final PBFTClient pbftClient = PBFTClient.getInstance();

    public BlockchainWebSocketClient(URI serverUri) {
        super(serverUri);
    }

    /**
     * 与服务端连接后 向服务端发送自己的node节点进行初始化
     * 同时将当前与服务端的连接socket保存在PBFTClient的sockets列表里 当需要广播消息的时候 遍历列表广播即可
     *
     * @param serverHandshake
     */
    @Override
    public void onOpen(ServerHandshake serverHandshake) {
        //将socket保存到sockets列表中
        pbftClient.getSockets().add(this);
        //如果是消息客户端节点就不用发初始化消息 不然会报错
        if (Node.getInstance().getIndex() == -1) {
            return;
        }

        PBFTMsg pbftMsg = new PBFTMsg();
        Node node = new Node();
        BeanUtil.copyProperties(Node.getInstance(), node);
        node.setPrivateKey(null);
        pbftMsg.setNode(node);
        pbftMsg.setMsgType(PBFTMsgType.INIT.getCode());
        this.send(JSON.toJSONString(pbftMsg));
    }

    /**
     * 客户端不接收消息
     *
     * @param msg
     */
    @Override
    public void onMessage(String msg) {
        log.info(msg);
    }

    @Override
    public void onClose(int i, String s, boolean b) {
        System.out.println("客户端关闭：" + this.getLocalSocketAddress());
        pbftClient.getSockets().remove(this);
    }

    @Override
    public void onError(Exception e) {
        System.out.println("客户端报错" + e);
        pbftClient.getSockets().remove(this);
    }
}
